package controller;

import model.Person;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import service.PersonService;

@Controller
public class PersonController {

	@Autowired
	private PersonService personService;

	@RequestMapping(value = "/person", method = RequestMethod.GET)
	public String getPersonList(ModelMap model) {
		model.addAttribute("personList", personService.listPerson());
		return "output";
	}

	@RequestMapping(value = "/findByName", method = RequestMethod.GET)
	public String findName(@RequestParam("name") String name, ModelMap model) {
		model.addAttribute("personList", personService.listPerson());
		model.addAttribute("personListByName",
				personService.findPersonByName(name));
		return "output";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public View createPerson(@ModelAttribute Person person) {
		personService.addPerson(person);
		return new RedirectView("/SpringMongoDB1/person");
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public View deletePerson(@ModelAttribute Person person) {
		personService.deletePerson(person);
		return new RedirectView("/SpringMongoDB1/person");
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public View updatePerson(@ModelAttribute Person person) {
		personService.updatePerson(person);
		return new RedirectView("/SpringMongoDB1/person");
	}

}
